package app

import (
	// "fmt"
	// "os"
	// "path/filepath"
	"time"

	"github.com/go-apibox/utils"
)

func (app *App) initDB() error {
	engine, err := app.API.DB.GetSqlite3("default")
	if err != nil {
		return err
	}

	app.engine = engine

	if _, err := engine.Exec(SQL_CREATE_TABLE_USER); err != nil {
		return err
	}
	if _, err := engine.Exec(SQL_CREATE_TABLE_DeviceGroup); err != nil {
		return err
	}
	if _, err := engine.Exec(SQL_CREATE_TABLE_Device); err != nil {
		return err
	}
	if _, err := engine.Exec(SQL_CREATE_TABLE_task); err != nil {
		return err
	}
	if _, err := engine.Exec(SQL_CREATE_TABLE_TaskProduct); err != nil {
		return err
	}
	if _, err := engine.Exec(SQL_CREATE_TABLE_TaskConfig); err != nil {
		return err
	}
	if _, err := engine.Exec(SQL_CREATE_TABLE_TaskLog); err != nil {
		return err
	}
	if _, err := engine.Exec(SQL_CREATE_TABLE_task_group); err != nil {
		return err
	}

	return nil
}

func (app *App) initConfig() (err error) {
	app.config = newDefaultConfig()

	app.config.DataDir = app.API.Config.GetDefaultString("app_config.data_dir", app.config.DataDir)
	app.config.AdminPasswd = app.API.Config.GetDefaultString("app_config.admin_pw", app.config.AdminPasswd)
	app.config.AdminName = app.API.Config.GetDefaultString("app_config.admin_name", app.config.AdminName)
	app.config.AdminEmail = app.API.Config.GetDefaultString("app_config.admin_email", app.config.AdminName)

	return nil

}

func (app *App) initAdmin() error {

	admin := new(User)
	has, err := app.engine.Where("email=?", app.config.AdminEmail).Get(admin)
	if err != nil {
		return err
	}
	if has {
		app.adminUser = admin
		return nil
	}

	admin = &User{
		UserId:     utils.RandUint32(),
		UserName:   app.config.AdminName,
		Email:      app.config.AdminEmail,
		Password:   SealPW(app.config.AdminPasswd),
		Status:     USER_STATUS_NORMAL,
		Desc:       "Smaug",
		UserType:   USER_TYPE_ADMIN,
		CreateTime: uint32(time.Now().Unix()),
	}

	if _, err = app.engine.Insert(admin); err != nil {
		return err
	}

	app.adminUser = admin
	return nil
}
